package com.dragon8869.myspringboot.error;


import com.dragon8869.myspringboot.exception.BusinessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@ControllerAdvice(basePackages = {"com.dragon8869.myspringboot"})
public class GlobalExceptionHandler {

    @ExceptionHandler({BusinessException.class})
    @ResponseBody
    private ErrorInfo<?> businessExceptionErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception exception){
        ErrorInfo<Object> errorInfo = new ErrorInfo<>();
        errorInfo.setMessage(exception.getMessage());
        errorInfo.setUrl(request.getRequestURI());
        errorInfo.setCode(ErrorInfo.ERROR);
        response.setCharacterEncoding("utf-8");
        return errorInfo;
    }

    @ExceptionHandler(IOException.class)
    private String IOExceptionErrorHandler(HttpServletRequest request, HttpServletResponse response){
        return "redirect:/404.html";
    }
}
